package cn.tedu.store.service.impl;

import cn.tedu.store.entity.Address;
import cn.tedu.store.entity.Order;
import cn.tedu.store.entity.OrderItem;
import cn.tedu.store.mapper.OrderMapper;
import cn.tedu.store.service.IAddressService;
import cn.tedu.store.service.ICartService;
import cn.tedu.store.service.IOrderService;
import cn.tedu.store.service.ex.InsertException;
import cn.tedu.store.vo.CartVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
@Service
public class OrderServiceImpl implements IOrderService {
	@Autowired
	private OrderMapper orderMapper;
	@Autowired
	private IAddressService addressService;
	@Autowired
	private ICartService cartService;
	
	private void insertOrder(Order order) throws InsertException{
		Integer rows=orderMapper.insertOrder(order);
		if (rows!=1) {
			throw new InsertException("插入订单数据失败！");
		}
	}
	
	private void insertOrderItem(OrderItem orderItem) throws InsertException{
		
		Integer rows=orderMapper.insertOrderItem(orderItem);
		if (rows!=1) {
			throw new InsertException("插入订商品明细单数据失败！");
		}
	}

	@Override
	@Transactional
	public Order  creat(Integer aid, Integer[] cids, Integer uid, String username) throws InsertException {
		Address address=addressService.getByAid(aid);
		//TODO 判断地址是否存在
		Date now=new Date();
		List<CartVO> carts=cartService.getByCids(cids, uid);
		Long total_price=0L;
		for (CartVO item:carts) {
			total_price+=item.getPrice()*item.getNum();
		}
		//插入订单
		Order order=new Order();
		order.setUid(uid);
		order.setRecv_name(address.getName());
		order.setRecv_phone(address.getPhone());
		order.setRecv_address(address.getProvince_name()+address.getCity_name()+address.getArea_name()+address.getAddress());
		order.setTotal_price(total_price);
		order.setState(0);
		order.setOrder_time(now);
		//支付后才写入支付时间，在其他Service中做
		order.setPay_time(null);
		order.setCreated_user(username);
		order.setCreated_time(now);
		order.setModified_user(username);
		order.setModified_time(now);
		insertOrder(order);
		
		//插入订单商品明细
		for (CartVO cartVO:carts) {
			OrderItem orderItem=new OrderItem();
			//oid在上面执行插入订单后自动获得,需在Ordermapper.xml中配置
			orderItem.setOid(order.getOid());
			orderItem.setGid(cartVO.getGid());
			orderItem.setPrice(cartVO.getPrice());
			orderItem.setTitle(cartVO.getTitle());
			orderItem.setImage(cartVO.getImage());
			orderItem.setNum(cartVO.getNum());
			orderItem.setCreated_user(username);
			orderItem.setCreated_time(now);
			orderItem.setModified_user(username);
			orderItem.setModified_time(now);
			insertOrderItem(orderItem);
		}
		
		//TODO 减少库存
		
		//TODO 删除订单数据
		return order;
	}
	

}
